<?php

namespace App\Services\Command;

use App\Exceptions\MsgException;
use App\Patent;
use App\PatentApply;
use App\PatentFee;
use App\Services\PatentService;
use App\Setting;
use App\Transaction;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;

//php artisan command:modify {function}
class ModifyCommandService
{
    //php artisan command:modify checkPatentSn
    public function checkPatentSn()
    {
        $res = Patent::query()->whereIn('patent_type_id', [1, 2, 3])->pluck('patent_sn', 'patent_sn')
            ->filter(function ($sn) {
                return !patent_sn_match($sn);
            })->toArray();
        dump($res);
    }

    protected function getClient($base_uri = '', $timeout = 60)
    {
        $config = ['timeout' => $timeout];
        if ($base_uri) {
            $config['base_uri'] = $base_uri;
        }
        return new Client($config);
    }

    protected function gatherPatentDJF($list, $authorization, $size = 100)
    {
        $host = 'https://qyapi.weixin.qq.com';
        $url = 'https://api.cponline.cnipa.gov.cn/zljffw/fycx/yjfywbl/listyjf-batchhdpage';
        $headers = [
            'Accept'        => 'application/json, text/plain, */*',
            'Content-Type'  => 'application/json;charset=UTF-8',
            'Authorization' => $authorization,
            'User-Agent'    => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.22',
        ];
        $response = [];
        $client = $this->getClient($host);
        try {
            $res = $client->post($url, ['headers' => $headers, 'json' => ['zhuanlisqhs' => $list, 'size' => $size, 'current' => 1]]);
            $content = $res->getBody()->getContents();
            $result = json_decode($content, true) ?: [];
            $code = data_get($result, 'code');
            if ($code == 200) {
                $records = $result['result']['records'];
                foreach ($records as $record) {
                    $patent_sn = data_get($record, 'shenqingh');
                    $response[$patent_sn] = collect(data_get($record, 'feeList', []))
                        ->map(function ($item) use ($patent_sn) {
                            return [
                                'patent_sn' => $patent_sn,
                                'name'      => $item['feiyongmc'],
                                'amount'    => $item['feiyongbz'],
                                'last_time' => $item['jiaofeiqxjmr'],
                            ];
                        })->all();
                }
            } else {
                dump('请求失败-------------');
                dump($result);
            }
        } catch (\Exception $exception) {
            dump($exception->getMessage());
        }
        return $response;
    }

    //php artisan command:modify syncPatentFee
    public function syncPatentFee()
    {
        $config = Setting::getSettings('sync')->pluck('value', 'slug');
        $authorization = $config->get('sync_secret');
        $sync_patent_type = $config->get('sync_patent_type') ?: '1,2,3';
        if ($authorization) {
            $types = explode(',', $sync_patent_type);
            Patent::query()->select(['patent_sn', 'user_id'])
                ->where('is_monitor', 1)
                ->whereIn('patent_type_id', $types)
                ->chunk(50, function (Collection $list) use ($authorization) {
                    $user_ids = $list->pluck('user_id', 'patent_sn');
                    $data = $this->gatherPatentDJF($list->pluck('patent_sn')->toArray(), $authorization);
                    collect($data)->map(function ($item, $key) use ($user_ids) {
                        $user_id = $user_ids->get($key) ?: 0;
                        $inserts = collect($item)->map(function ($item) use ($user_id) {
                            return array_merge($item, [
                                'user_id'    => $user_id,
                                'created_at' => Carbon::now(),
                                'updated_at' => Carbon::now(),
                            ]);
                        });
                        try {
                            $collect = collect([]);
                            $list = PatentFee::query()->where('patent_sn', $key)->get();
                            foreach ($list as $item) {
                                if ($inserts->where('name', $item['name'])->where('amount', $item['amount'])->where('last_time', $item['last_time'])->first()) {
                                    $collect->push($item);
                                } else {
                                    $item->delete();
                                }
                            }
                            $inserts = $inserts->filter(function ($item) use ($collect) {
                                return !$collect->where('name', $item['name'])->where('amount', $item['amount'])->where('last_time', $item['last_time'])->first();
                            })->values()->all();
                            if ($inserts) {
                                PatentFee::query()->insert($inserts);
                                dump('更新完成' . count($inserts));
                            }
                        } catch (\Exception $exception) {
                            dump($exception->getMessage());
                            dump($inserts);
                        }
                    });
                });
        } else {
            dump('设置错误--------------');
        }
    }


    //php artisan command:modify patentState
    public function patentState()
    {
        Patent::query()->has('transaction')->where('state', 1)->get()
            ->map(function ($patent) {
                $patent->state = 2;
                $patent->save();
            });
    }


    //php artisan command:modify changePatentSn
    public function changePatentSn()
    {
        Patent::query()
            ->whereIn('patent_type_id', [1, 2, 3])
            ->get()
            ->map(function ($model) {
                try {
                    $patent_sn = PatentService::check_patent_sn($model->patent_sn, $model->patent_type_id);
                    try {
                        if ($model->patent_sn != $patent_sn) {
                            $model->patent_sn = $patent_sn;
                            $model->save();
                        }
                    } catch (\Exception $exception) {

                    }
                } catch (MsgException $exception) {
                }
            });
        dump('patent end ----------------------------------');
        PatentApply::query()
            ->whereIn('patent_type_id', [1, 2, 3])
            ->get()
            ->map(function ($model) {
                try {
                    $patent_sn = PatentService::check_patent_sn($model->patent_sn, $model->patent_type_id);
                    if ($model->patent_sn != $patent_sn) {
                        $model->patent_sn = $patent_sn;
                        $model->save();
                    }
                } catch (MsgException $exception) {
                }
            });
        dump('PatentApply end ----------------------------------');
        Transaction::query()
            ->whereIn('patent_type_id', [1, 2, 3])
            ->get()
            ->map(function ($model) {
                try {
                    $patent_sn = PatentService::check_patent_sn($model->patent_sn, $model->patent_type_id);
                    if ($model->patent_sn != $patent_sn) {
                        $model->patent_sn = $patent_sn;
                        $model->save();
                    }
                } catch (MsgException $exception) {
                }
            });
        dump('Transaction end ----------------------------------');
    }


}
